package com.myvision.config;

import java.io.IOException;
import java.io.InputStream;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class MenuConfig {

	private static Log log = LogFactory.getLog(MenuConfig.class);

	private static final String DATA_PATH = "/WEB-INF/menu-config.xml";

	private Document doc = null;

	private static MenuConfig instance;

	public static MenuConfig getInstance() {
		if (instance == null) {
			instance = new MenuConfig();
		}
		if (log.isDebugEnabled()) {
			log.debug("Getting MenuConfig Instance.");
		}
		return instance;
	}

	public synchronized Document getDoc() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ExternalContext externalContext = facesContext.getExternalContext();

		InputStream dataStream = externalContext.getResourceAsStream(DATA_PATH);

		if (doc == null) {
			if (log.isDebugEnabled()) {
				log.debug("Loading Menu Config file from " + DATA_PATH);
			}
			try {
				doc = new SAXBuilder().build(dataStream);
			} catch (JDOMException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (dataStream != null) {
					try {
						dataStream.close();
					} catch (IOException e) {
						externalContext.log(e.getMessage(), e);
					}
				}
			}
		}
		return doc;
	}
}
